import React, { Component } from "react";
import { connect } from "dva";
import cn from "classnames";
import moment from "moment";
import WeekCalendar from "components/calendar/WeekCalendar";
import { omit } from "utils/comm";
import styles from "./index.less";
import DateCellPopover from "./DateCellPopover/DateCellPopover";

@connect(({ weekdaysManagement: { workingDayList, specialDayTemp, specialDay, realSpecialDay, selectedYear } }) => ({
  workingDayList, specialDayTemp, specialDay, realSpecialDay, selectedYear,
}))
class StepTwo extends Component {
  state = {
    popVisible: null,
    startDate: undefined,
    endDate: undefined,
  };

  getData = (date) => {
    const { dispatch } = this.props;
    dispatch({
      type: "weekdaysManagement/getOffDayList",
      queryMoment: date,
    });
  };

  handleSelect = (value) => {
    const date = value.format("YYYY-MM-DD");
    const { popVisible } = this.state;
    if (popVisible !== date) {
      this.setState({
        popVisible: date,
      });
    }
  };

  handleCalendarChange = (date) => {
    this.getData(date);
  };

  handleVisibleChange = (date, visible) => {
    if (!visible) {
      this.setState({
        startDate: undefined,
        endDate: undefined,
      });
    }
    this.setState({ popVisible: visible ? date : "" });
  };


  handleRangeChangeComplete = ([rangeStart, rangeEnd]) => {
    // rangeStart
    const { popVisible } = this.state;
    if (popVisible !== rangeEnd.format("YYYY-MM-DD")) {
      this.setState({
        popVisible: rangeEnd.format("YYYY-MM-DD"),
        startDate: rangeStart.format("YYYY-MM-DD"),
        endDate: rangeEnd.format("YYYY-MM-DD"),
      });
    }
    ;
  };

  handlePropsChange = (date, { type, remark } = {}) => {
    const { specialDay, dispatch } = this.props;
    const { specialDayTemp } = this.props;
    const { startDate = date, endDate = date } = this.state;
    let startTemp = startDate;
    let specialDayCur = {};
    const dates = [];
    for (startTemp; startTemp <= endDate; startTemp = moment(startTemp).add(1, "days").format("YYYY-MM-DD")) {
      dates.push(startTemp);
      if (type) {
        specialDayCur [startTemp] = { start: `${startTemp} 00:00:00`, type, remark };
        specialDayCur = {
          ...specialDayTemp,
          ...specialDayCur,
        };
      }
      if (!type) {
        if (specialDay[startTemp]) {
          specialDayCur[startTemp] = { removed: true };
          specialDayCur = {
            ...specialDayTemp,
            ...specialDayCur,
          };
        } else if (specialDayTemp[startTemp]) {
          // const { [startTemp]: removed, ...leftSpecialDayTemp } = specialDayTemp;
          const leftSpecialDayTemp = omit(specialDayTemp, dates);
          specialDayCur = leftSpecialDayTemp;
        }
      }
    }
    if (!type && JSON.stringify(specialDayCur) !== "{}") {
      /* 删除 */
      dispatch({
        type: "weekdaysManagement/set/SpecialDayTemp",
        specialDayTemp: specialDayCur,
      });
      /* if (specialDay[date]) {
         console.log("date--------", date);
         dispatch({
           type: "weekdaysManagement/set/SpecialDayTemp",
           specialDayTemp: {

             [date]: { removed: true },
           },
         });
       } else if (specialDayTemp[date]) {
         const { [date]: removed, ...leftSpecialDayTemp } = specialDayTemp;
         console.log("leftSpecialDayTemp-----------", leftSpecialDayTemp);
         dispatch({
           type: "weekdaysManagement/set/SpecialDayTemp",
           specialDayTemp: leftSpecialDayTemp,
         });
       } */
    } else if (JSON.stringify(specialDayCur) !== "{}") {
      /* 修改 */
      dispatch({
        type: "weekdaysManagement/set/SpecialDayTemp",
        specialDayTemp: specialDayCur,
      });
    }
  };


  renderDateCell = (value, range, inRange) => {
    const { workingDayList, realSpecialDay } = this.props;

    const { popVisible } = this.state;
    let startStr = null;
    let endStr = null;
    if (inRange && range) {
      const [startMoment, endMoment] = range;
      startStr = startMoment.format("MMMDo");
      endStr = endMoment.format("MMMDo");
    }

    const date = value.format("YYYY-MM-DD");
    const week = value.format("ddd");

    const dateDetail = realSpecialDay[date];
    const dateWork = workingDayList.find((item) => (item.name === week));

    const title = startStr && endStr && startStr !== endStr ? `${startStr}-${endStr}` : value.format("MMMDo");

    const { type, remark } = dateDetail || {};
    return (
      <DateCellPopover
        placement="right"
        title={title}
        trigger="click"
        visible={popVisible === date}
        onVisibleChange={(visible) => this.handleVisibleChange(date, visible)}
        type={type}
        remark={remark}
        onPropsChange={(props) => this.handlePropsChange(date, props)}
      >
        {dateDetail == null || dateDetail.removed ? (
          <div className={cn(styles.detail, { [styles.offDay]: !dateWork })} />
        ) : (
          <div className={cn(styles.special, { [styles.offDay]: !dateWork })}>
            {dateDetail.type === "OFF_DAY" ?
              <div className={styles.tag}>休</div> :
              dateDetail.type === "WORKING_DAY" ?
                <div className={styles.tag} style={{ background: "#f65858" }}>班</div> : null}
            <div className={styles.desc}>{dateDetail.remark}</div>
          </div>
        )}
      </DateCellPopover>
    );
  };

  render() {
    const { selectedYear } = this.props;
    return (
      <div className={styles.root}>
        <WeekCalendar
          rangeMode
          value={moment(selectedYear)}
          dateCellRender={this.renderDateCell}
          onSelect={this.handleSelect}
          onPanelChange={this.handleCalendarChange}
          onRangeChangeComplete={([rangeStart, rangeEnd]) => {
            this.handleRangeChangeComplete([rangeStart, rangeEnd]);
          }}
        />
      </div>
    );
  }
};

export default StepTwo;
